﻿using System.Xml.Linq;
using BattleFury.Lib.Extensions;
using Microsoft.Xna.Framework;

namespace BattleFury.Lib.Controls
{
	public class ProgressBar
		: Control
	{
		public static string PartBorderLeft = "ProgressBarLeft";
		public static string PartBorderCenter = "ProgressBarCenter";
		public static string PartBorderRight = "ProgressBarRight";

		public static string PartFill = "ProgressBarFill1";

		public double Value { get; set; }
		public double Minimum { get; set; }
		public double Maximum { get; set; }
		public Color FillColor { get; set; }
		public Color BorderColor { get; set; }

		public ProgressBar()
		{
			FillColor = Color.White;
			BorderColor = Color.White;
		}

		public override void Deserialize(XElement element, object callingObject)
		{
			base.Deserialize(element, callingObject);

			Value = element.GetDouble("Value", 0.0);
			Minimum = element.GetDouble("Minimum", 0.0);
			Maximum = element.GetDouble("Maximum", 100.0);
			FillColor = element.GetColor("FillColor", Color.White);
			BorderColor = element.GetColor("BorderColor", Color.White);
		}

		public override void Update(GameTime gameTime)
		{
			if (Value > Maximum) Value = Maximum;
			if (Value < Minimum) Value = Minimum;
		}

		public override void Draw(GameTime gameTime)
		{
			var leftPart = Skin[PartBorderLeft];
			var centerPart = Skin[PartBorderCenter];
			var rightPart = Skin[PartBorderRight];
			var fillPart = Skin[PartFill];

			var innerWidth = Size.X - leftPart.Width - rightPart.Width;
			var percent = Value / (Maximum - Minimum);

			var fillRect = new Rectangle((int)(Position.X), (int)Position.Y, (int)(percent * Size.X), (int)(Size.Y));
			SpriteBatch.Draw(Texture, fillRect, fillPart.SourceBounds, FillColor);

			// Border
			SpriteBatch.Draw(Texture, Position, leftPart.SourceBounds, BorderColor);

			for (var i = 0; i < innerWidth; i += centerPart.Width)
			{
				SpriteBatch.Draw(Texture, Position + new Vector2(i + centerPart.Width, 0f), centerPart.SourceBounds, BorderColor);
			}

			SpriteBatch.Draw(Texture, Position + new Vector2(innerWidth + centerPart.Width, 0f), rightPart.SourceBounds, BorderColor);
		}
	}
}